package com.liutaw.nanjingair.utils;

import android.os.AsyncTask;

import com.liutaw.nanjingair.views.activities.products.IImportantWeatherView;

import java.io.File;
import java.io.IOException;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okio.BufferedSink;
import okio.Okio;

/**
 * Created by liutao on 16/3/16.
 */
public class DowloaderTask extends AsyncTask<String, Integer, File> {

    private IImportantWeatherView ipdfReaderController;

    public DowloaderTask(IImportantWeatherView ipdfReaderController) {
        this.ipdfReaderController = ipdfReaderController;
    }

    @Override
    protected void onPostExecute(File file) {
//        super.onPostExecute(file);
//        ipdfReaderController.onDownloadPdfFileCompleted(file);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected File doInBackground(String... params) {
        if (params.length < 3)
            return null;
        final String pdfUrl = params[0];
        final String filePath = params[1];
        final String fileName = params[2];
        ipdfReaderController.onDownloadingProgress();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request requestBody = new Request.Builder().url(pdfUrl).build();
        final File downloadedFile = new File(filePath, fileName);
        okHttpClient.newCall(requestBody).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                ipdfReaderController.onDownloadingFailed(e.getMessage());
            }

            @Override
            public void onResponse(Response response) throws IOException {
//                InputStream inputStream = response.body().byteStream();
                if (response.isSuccessful()) {
                    BufferedSink sink = Okio.buffer(Okio.sink(downloadedFile));
                    sink.writeAll(response.body().source());
                    sink.flush();
                    sink.close();
                    ipdfReaderController.onDownloadPdfFileCompleted(downloadedFile);
                } else {
                    ipdfReaderController.onDownloadingFailed(response.message());
                }

            }
        });
        return downloadedFile;
    }
}
